package com.zxxy.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.zxxy.common.utils.R;
import com.zxxy.gulimall.cart.feign.ProdectFeignService;
import com.zxxy.gulimall.cart.interceptor.CartInterceptor;
import com.zxxy.gulimall.cart.service.CartService;
import com.zxxy.gulimall.cart.vo.Cart;
import com.zxxy.gulimall.cart.vo.CartItem;
import com.zxxy.gulimall.cart.vo.SkuInfoVo;
import com.zxxy.gulimall.cart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProdectFeignService prodectFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    private final String CART_PREFIX = "gulimall:cart:";

    @Override
    public CartItem addToCart(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(res)){
            // 2、添加新商品到购物车
            // 1、远程查询当前要添加的商品的信息
            CartItem cartItem = new CartItem();
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                R info = prodectFeignService.info(skuId);
                SkuInfoVo data = info.getData(new TypeReference<SkuInfoVo>() {
                });
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setSkuId(skuId);
                cartItem.setPrice(new BigDecimal("23"));
            },executor);

            // 3、远程查询sku的组合信息
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                List<String> values = prodectFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(values);
            }, executor);
            try {
                CompletableFuture.allOf(getSkuInfoTask,getSkuSaleAttrValues).get();
                System.out.println("---------------"+cartItem);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            String s = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(),s);
            return cartItem;
        }else {
            // 购物车有此商品，修改数量
            CartItem item = JSON.parseObject(res, CartItem.class);
            item.setCount(item.getCount()+num);
            cartOps.put(skuId.toString(),JSON.toJSONString(item));
            return item;
        }
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String str = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(str, CartItem.class);
        cartItem.setSkuId(skuId);
        return cartItem;
    }

    @Override
    public Cart getCart() {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId()!=null){
            // 1、登录
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            // 2、如果临时购物车的数据还没有合并
            String tempCartKey =CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> tempCartItems = getCartItems(tempCartKey);
            if (tempCartItems!=null){
                for (CartItem item : tempCartItems){
                    addToCart(item.getSkuId(),item.getCount());
                }
                // 清除临时购物车的数据
                clearCart(tempCartKey);
            }
            // 3、获取登录后的购物车的数据【包含合并过来的临时购物车的数据，和登录后的购物车的数据】
            List<CartItem> cartItems = getCartItems(cartKey);
            cartItems.get(0).setSkuId(1L);
            cart.setItems(cartItems);
        }else {
            // 2、没登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }


        return cart;
    }

    // 获取到我们要操作的购物车
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey  = "";
        // gulimall:cart:1
        if (userInfoTo.getUserId()!=null){
            cartKey = CART_PREFIX+ userInfoTo.getUserId();
        }else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }

    private List<CartItem> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (values!=null && values.size()>0){
            List<CartItem> collect = values.stream().map((obj) -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }

        return null;
    }

    @Override
    public void clearCart(String cartKey){
        redisTemplate.delete(cartKey);

    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);

        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);


    }


    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));

    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null){
            return null;
        }else {
            String cartKey = CART_PREFIX+ userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            System.out.println(cartItems.get(0).getCheck()+"-------------"+cartItems.get(0).getSkuId());
            for (CartItem item:cartItems){
                //R price = prodectFeignService.getPrice(item.getSkuId());
                R price = prodectFeignService.getPrice(1L);
                String data = (String) price.get("data");
                item.setPrice(new BigDecimal(data));
            }
            // 获取所有被选中的购物项
           /* List<CartItem> collect = cartItems.stream()
                    //.filter(item -> item.getCheck())
                    .map(item->{
                        R price = prodectFeignService.getPrice(item.getSkuId());
                        // TODO 跟新为最新价格
                        String data = (String) price.get("data");
                        item.setPrice(new BigDecimal(data));
                        return item;
                    })
                    .collect(Collectors.toList());*/
            return cartItems;
        }
    }

}
